package com.pzr.soccer.filter;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
@Slf4j
public class CheckTokenFilter implements GlobalFilter, Ordered {
    @Value("${allow.noToken.access.url:/user/login,/user/validate/code,/test/**}")
    private Set<String> allowNoTokenAccessUrls;
    /**
     *实现判断用户是否携带token，token是否过期或错误的filter
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //不用token的情况
        if(allowNoTokenAccess(exchange)){
            log.info("no need token");
            return  chain.filter(exchange);
        }
        //取出token
        String tokenStr = getToken(exchange);
        // 在redis是否有这个token（实现token失效）

        // token是否有效
        if(tokenStr==null||tokenStr.isBlank()){
            return  buildUnauthorizedResult(exchange);
        }
        log.info("token check pass!");
        return chain.filter(exchange);
    }



    private Mono<Void> buildUnauthorizedResult(ServerWebExchange exchange) {
        ServerHttpResponse response=exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().set("content-type","application/json;Charset=UTF-8");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error", "unauthorized");
        jsonObject.put("error_description", "invalid token");
        DataBuffer dataBuffer = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(dataBuffer));
    }

    private String getToken(ServerWebExchange exchange) {
        HttpHeaders headers=exchange.getRequest().getHeaders();
        String auth=headers.getFirst(HttpHeaders.AUTHORIZATION);
        if(auth==null||auth.isBlank()){
            return  null;
        }
        return  auth.replace("bearer","");
    }

    private boolean allowNoTokenAccess(ServerWebExchange exchange) {
        String path=exchange.getRequest().getURI().getPath();
        return this.allowNoTokenAccessUrls.contains(path);
    }

    @Override
    public int getOrder() {
        return 0;
    }


}
